/**
 * Project trunk.
 * User: hp-stuff
 * Date: 4/16/13
 * Time: 2:01 PM
 * To change this template use File | Settings | File Templates.
 */
DropDown = (function (_super) {

    __extends(DropDown, _super);

    function DropDown(view) {
        var _this = this;
        DropDown.__super__.constructor.call(this);
        this.setContentView(view);

        this.isOpen = false;
        this.isClosed = true;
        this.wrapper = new View("wrapper");
        this.display = new Button(this.view.select(".display", true));

        this.display.view.bind("touchstart", function(e){
            _this.isClosed = !_this.isClosed;
        });
        this.display.setOnClickListener(function(e){
            if(_this.isOpen){
                _this.close();
            }else{
                _this.open();
            }
        });
        this.setItemTemplate();
        this.list = new List(this.view.select("ul"), this.itemTemplate);
        this.list.setOnItemSelectedListener(function(){
            _this.setSelected(this);
        });
        this.list.view.hide();
    }

    DropDown.prototype.setItems = function(data){
        this.list.setItems(data);
        this.setSelected(this.list.items[0]);
    };

    DropDown.prototype.setSelected = function(item){
        var _selected = this.list.view.select(".selected");
        if(_selected) _selected.removeClass("selected");
        (this.selected = item).view.addClass("selected");
        this.setDisplayText(this.selected.data);
        if(this.selectedListener) this.selectedListener.call(this.selected);
        this.close();
    };

    DropDown.prototype.setOnItemSelectedListener = function(listener){
        this.selectedListener = listener;
    };

    DropDown.prototype.setItemTemplate = function(id){
        this.itemTemplate = id || "<%=obj%>"
    };

    DropDown.prototype.setDisplayText = function(text){
        this.display.view.html(text);
    };

    DropDown.prototype.getSelectedItem = function(){
        return this.selected;
    };

    DropDown.prototype.open = function(){
        var _this = this;
        this.isOpen = true;
        this.list.view.show();
        this.wrapper.bind("touchstart", function(e){
            if(!_this.isClosed) _this.close();
        });

    };

    DropDown.prototype.close = function(){
        var _this = this;
        this.isOpen = false;
        setTimeout(function(){
            _this.list.view.hide();
        },200);
        this.wrapper.unbind("touchstart");
    };

    return DropDown;

})(Base);